import axios from "axios";
import qs from "qs";
import { ElMessage } from 'element-plus'
import router from "@/router";
axios.defaults.baseURL = "https://www.biokeylab.com/api";
// axios.defaults.baseURL = "http://39.101.75.6/api";
// axios.defaults.baseURL = "http://localhost:8000/api";


// 1、请求拦截
axios.interceptors.request.use(
    config => {
        let token = window.localStorage.getItem('token');
        config.headers.Authorization = "Bearer " + token;
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);
// 2、响应拦截
axios.interceptors.response.use(
    res => {
        return res;
    },
    error => {
        if (error && error.response) {
            const status = error.response.status;
            switch (status) {
                case 401:
                    router.push('/login');
                    ElMessage.error("未授权，请重新登录");
                    break;
                case 403:
                    router.push('/login');
                    ElMessage.error("拒绝访问");
                    break;
            }
        } else {
            if (JSON.stringify(error).includes("timeout")) {
                ElMessage.error("服务器响应超时，请刷新页面")
            } else {
                ElMessage.error("连接服务器失败")
            }
        }
        router.push('/login');
        return Promise.reject(error);
    }
);


export default {
    post(url, data){
        return new Promise((resolve, reject) =>{
            axios({
                method: 'post',
                url,
                data: qs.stringify(data)
            }).then(res =>{
                resolve(res.data)
            }).catch(err=>{
                reject(err)
            })
        })
    }
}